package com.qf.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.openapi2204.common.constants.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Component
public class RoutingFilter extends ZuulFilter {



    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {

        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean result = currentContext.sendZuulResponse();

        return result;
    }

    @Override
    public Object run() throws ZuulException {

        //1. 从请求参数中获取 method 的值
        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();

        String method = request.getParameter("method");

        //2. 从缓存模块中查询 method 对于的路由信息
        String prefix = RedisConstants.APINAME_PREFIX;
        String id = method;
        String key = prefix+":"+id;

        // 2.1 先查询本地缓存中是否有对于的路由信息
//        HashMap<String, Object> routingInfo = LocalCache.routingCache.get(key);
//
//        if (routingInfo ==null || routingInfo.size()==0){
//            // 本地缓存没有对于的路由信息，进行feign调用
//            ResultVo resultVo = cacheClient.hgetAll(key);
//            routingInfo = (HashMap<String, Object>) resultVo.getData();
//
//            // 把查询到的路由信息写入本地缓存中
//            LocalCache.routingCache.put(key,routingInfo);
//        }

        HashMap<String, Object> routingInfo = new HashMap<>();
        routingInfo.put("serviceId","wxpay");
        routingInfo.put("insideApiUrl","/getpayurl");

        //3. 根据查询到的 微服务名和 微服务的接口url路径 ，进行动态路由
        String serviceId = (String) routingInfo.get("serviceId");
        String insideApiUrl = (String) routingInfo.get("insideApiUrl");

        System.out.println(serviceId+":"+insideApiUrl);
        // 如何进行动态路由
        // FilterConstants.SERVICE_ID_KEY 这个常量代表，要zuul网关把当前请求发送给哪个微服务，value部分写微服务的名字
        currentContext.set(FilterConstants.SERVICE_ID_KEY,serviceId);

        // FilterConstants.REQUEST_URI_KEY，这个常量代表
        currentContext.set(FilterConstants.REQUEST_URI_KEY,insideApiUrl);

        return null;
    }
}
